package hello;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author Mark
 * @date 2020/5/25 17:52
 * @description cookie和session
 */
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            // 存在
            out.write("last visit time");
            for (Cookie cookie : cookies) {
                if ("lastTime".equals(cookie.getName())) {
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    out.write(date.toGMTString());
                }
            }
        } else {
            out.write("first entry");
        }

        // 避免中文传输乱码
        Cookie cookie = new Cookie("lastTime", URLEncoder.encode(System.currentTimeMillis() + "", "UTF-8"));
        resp.addCookie(cookie);

        //设置最大时间为0(意味着删除cookie)
        cookie.setMaxAge(0);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
